<?php
/**
 * Copyright (c) 2006-2008, Julien PORTALIER
 * 
 * Licensed under The LGPL License
 * Redistributions of files must retain the above copyright notice.
 * 
 * @copyright    Copyright (c) 2006-2008, Julien PORTALIER
 * @link         http://feather-cm.googlecode.com/
 * @license      http://www.opensource.org/licenses/lgpl-license.php The LGPL License
 */

class MembersController extends AppController
{
	public $restrictActions = array('index', 'my', /*'live',*/ 'invite', 'edit', 'password',
		'profile', 'avatar', 'allow_contact', 'close_welcome', 'delete', 'admin');
	public $uses       = 'Member';
	public $module     = 'member';
	public $_templates = 'members';
	
	function login()
	{
		if (HTTP::isPost())
		{
			$rs = $this->Member->login($this->params['form']['username'], $this->params['form']['password']);
			
			if (is_array($rs))
			{
				#. OK: logs user in
				$this->Auth->login($rs);
				
				# remember user?
				if (isset($this->params['form']['remember']))
					$this->Auth->remember($rs['id'], $rs['password']);
				
				# redirection
				if (isset($this->params['url']['redirect']))
					$redirect = urldecode($this->params['url']['redirect']);
				else
				{
					$redirect = isset($this->params['form']['redirect']) ?
						$this->params['form']['redirect'] : HTTP::getReferer();
				}
				
				# checks referer (to prevent an endless loop)
				if (empty($redirect) or !$this->Auth->checkReferer($redirect))
					$redirect = Core::login_redirect;
				
				$this->flash(sprintf(_('Welcome in %s!'), $rs['id']), $redirect);
			}
			
			#. ERROR
			if (!empty($rs))
				$this->Session->setFlash($rs, 'error');
		}
		
		$this->pageTitle = _('Login');
	}
	
	/**
	 * A (stupid) callback for automatic login.
	 * No need to authenticate, AuthComponent already did it!
	 */
	function auto_login()
	{
		$redirect = isset($this->params['url']['redirect']) ?
			urldecode($this->params['url']['redirect']) : HTTP::getReferer();
		HTTP::redirect($redirect);
	}
	
	function logout()
	{
		$this->Auth->logout();
		$this->flash(_("You are now disconnected. See you soon!"), '/', 'notice');
	}
	
	function my()
	{
		$this->data = $this->Member->read('*', $this->Auth->id);
		$this->pageTitle = _('My account');
	}
	
	function show($id)
	{
		$this->data = $this->Member->read('*', $id);
		$this->pageTitle = sprintf(_('%s - Member'), $id);
	}
	
	function live($q)
	{
		if (empty($q))
			exit;
		$this->data = $this->Member->search($q);
	}
	
	// account registration
	
	function register($invitation=null)
	{
		$this->pageTitle = _('Register');
		
		# invitation?
		$Invitation = $this->load->model('Invitation');
		if (defined('REGISTER_INVITATION_ONLY') and REGISTER_INVITATION_ONLY)
		{
			# we need a code!
			if (empty($invitation) and empty($this->data['Invitation']['md5']))
				return;
			else
			{
				# checks invitation
				$check = $Invitation->findByMd5(empty($invitation) ?
					$this->data['Invitation']['md5'] : $invitation);
				
				# invalid?
				if (empty($check))
				{
					$this->Session->setFlash(_('No such invitation code.'), 'error');
					return;
				}
				
				$invitation = $check['Invitation']['md5'];
				unset($data);
			}
		}
		
		# invited?
		if (!empty($invitation))
			$this->data['Invitation']['md5'] = $invitation;
		
		# registration
		if (!HTTP::isPost() or isset($this->params['form']['start']))
			$this->data['Member']['email'] = $Invitation->getField('email', $invitation);
		else
		{
			$groups = explode(',', str_replace(' ', '', Core::default_groups));
			
			# registers new member
			if ($this->Member->register($this->data['Member']['id'], &$groups))
			{
				if (!empty($invitation))
					$Invitation->erase($invitation);
				
				# logs member in
				$this->data['Member']['groups'] =& $groups;
				$this->Auth->login($this->data['Member']);
				
				# emails new member!
				$this->load->component('Swift');
				$this->Swift->addRecipient($this->data['Member']['email'], $this->data['Member']['id']);
				$this->Swift->send(_('Your account has been created'),
					array($this->Config->website['email'], $this->Config->website['name']));
				
				$this->flash(_('Your account has been created!'), '/my', 'notice');
			}
		}
	}
	
	// account management
	
	function admin($order='id', $way='ASC')
	{
		$page = isset($this->params['url']['page']) ? $this->params['url']['page'] : 1;
		
		if (empty($_GET['q']))
		{		
			$this->Member->order("Member.$order ".strtoupper($way));
			$this->data = $this->Member->getList(25, $page);
		}
		else
		{
			$this->Member->order("Member.$order ".strtoupper($way));
			$this->data = $this->Member->getListSearch($_GET['q'], 25, $page);
		}
		
		$this->pageTitle = _("Members' administration");
	}
	
	function reminder()
	{
#		if (isset($this->data['Member']['search']))
#		{
			if (!empty($this->data['Member']['search']))
			{
				# searches for an account
				$user = $this->Member->get($this->data['Member']['search']);
				
				if (!empty($user))
				{
					# crypts password
					$user['Member']['password'] = substr(md5(mt_rand()), 0, 8);
					list($data['salt'], $data['password']) = $this->Member->cryptPwd($user['Member']['password']);
					
					# records new password
					$this->Member->id = $user['Member']['id'];
					if ($this->Member->saveFields(&$data))
					{
						$this->set('user', &$user['Member']);
						
						# emails new password to member
						$this->load->component('Swift');
						$this->Swift->addRecipient($user['Member']['email'], $user['Member']['id']);
						$this->Swift->send(_('Your new password'), array($this->Config->website['email'], $this->Config->website['name']));
						
						$this->message(_("New password sent!"),
							_("Your new password has been sent to your email address. It should arrive soon."));
					}
					else {
						$this->Session->setFlash(_("An error occured."), 'error');
					}
				}
				else {
					$this->Session->setFlash(_("Error: no such account."), 'error');
				}
			 }
#			 else {
#				$this->Session->setFlash(_('You must enter a username or email.'), 'error');
#			 }
#		}
		$this->pageTitle = _('Password reminder');
	}
	
	function edit()
	{
		$this->Member->id = $this->Auth->id;
		
		if (empty($this->data))
			$this->data = $this->Member->read('id, email, allow_contact');
		else
		{
			$this->load->component('Security');
			$this->Security->restrictFieldsTo(array('Member' => 'id, email, allow_contact'));
			$this->data['Member']['allow_contact'] = isset($this->data['Member']['allow_contact']);
			
			if ($this->Member->save())
				$this->flash(_("Modifications to your account saved."), '/my', 'notice');
		}
	}
	
	function password()
	{
		$this->Member->id = $this->Auth->id;
		
		if (!empty($this->data))
		{
			$this->load->component('Security');
			$this->Security->restrictFieldsTo(array('Member' => 'old_password, password, password2'));
			
			if ($this->Member->save())
				$this->flash(_("Password changed."), '/my', 'notice');
		}
	}
	
	function profile()
	{
		$this->Member->id = $this->Auth->id;
		
		if (empty($this->data))
			$this->data = $this->Member->read();
		else
		{
			$this->load->component('Security');
			$this->Security->removeFields(array('Member' => 'id, email, allow_contact, old_password, password, password2'));
			
			if ($this->Member->save())
				$this->flash(_("Profile updated."), '/my', 'notice');
		}
	}
	
	function allow_contact($set=null)
	{
		$this->Member->id = $this->Auth->id;
		
		if (empty($set))
			$set = isset($this->data['Member']['allow_contact']);
		
		if ($this->Member->saveField('allow_contact', $set))
			$this->flash($set ? _('Your fans may now contact you.') : _("Your fans can't contact you anymore."), '/my', 'notice');
		else
			$this->flash(_('An error occured.'), '/my', 'error');
	}
	
	function close_welcome()
	{
		$this->Member->id = $this->Auth->id;
		$this->Member->saveField('welcome', null);
		exit;
	}
	
	function avatar()
	{
		Load::libs('avatar');
		
		if (HTTP::isPost())
		{
			try
			{
				$MemberAvatar = MemberAvatar::instance();
				if ($MemberAvatar->save($this->Auth->id) === UPLOAD_ERR_OK)
					$this->Session->setFlash(_('Avatar uploaded successfully.'), 'notice');
				else
					$this->Session->setFlash(_('No avatar was uploaded.'), 'error');
			}
			catch (Exception $e) {
				$this->Session->setFlash($e->getMessage(), 'error');
			}
		}
		$this->pageTitle = _("Upload an avatar");
	}
	/*
	function delete()
	{
		if (isset($this->params['url']['force']) and $this->params['url']['force'])
		{
			if ($this->Member->delete($this->Auth->id))
				$this->flash(_('Account deleted.'), '/');
			$this->flash(_('An error occured.'));
		}
		$this->pageTitle = _('Delete your account');
	}
	*/
}
?>